import { Component, ChangeDetectorRef, ChangeDetectionStrategy, Input } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { CompanyService } from "../../company.service";
import { Subscription } from "rxjs";
import { CompanyRiskRatingService } from "../companyRiskRating.service";
import { RiskCompanyModel } from "../models/riskCompany.model";
import { UtilsService } from "../../../../../shared/services/utils.service";
import { ClusterService } from "../../../riskCluster/cluster.service";
import { ClusterModel, ClusterModelWrapper } from "../../../riskCluster/cluster.model";
import { CompanyBaseWidget } from "../../shared/companyBaseWidget/companyBase.widget";

/**
 * Risk rating widget component
 * 
 * Author: Sorin Spiru
 * Date: 04.03.2018
 */
@Component({
    moduleId: module.id,
    templateUrl: './widget.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class WidgetComponent extends CompanyBaseWidget {
    private companySub: Subscription;
    private riskSub: Subscription;
    private clusterSub: Subscription;

    public roundUp: Function = UtilsService.roundUp;
    public researchStatusText: string;
    public currentClusterName: string;
    public riskCompany: RiskCompanyModel;

    constructor(
        private cdRef: ChangeDetectorRef,
        private route: ActivatedRoute,
        private router: Router,
        private companyService: CompanyService,
        private riskService: CompanyRiskRatingService,
        private clusterService: ClusterService) {
        super(route, router);
    }

    ngOnInit() {
        this.companySub = this.companyService.company.subscribe(company => {
            this.riskService.company = this.riskService.getCompanyById(company.id);
            this.clusterService.getCompanyRiskClusters();
            this.riskSub = this.riskService.company.subscribe(data => {
                this.riskCompany = data;
                this.researchStatusText = this.riskService.researchStatusText(data.availability);
                this.cdRef.markForCheck();                
                this.clusterSub = this.clusterService.company.subscribe(clusters => {
                    let cluster: ClusterModelWrapper = clusters.filter(function (cluster) {
                        return cluster.code == data.assessmentCode;
                    })[0];

                    this.currentClusterName = cluster != undefined ? cluster.name : "N/A";
                    this.cdRef.markForCheck();
                })

            });
        });
    }

    ngOndestroy() {
        this.riskSub.unsubscribe();
        this.companySub.unsubscribe();
        this.clusterSub.unsubscribe();
    }

    public navigateTo() {
        this.router.navigate(['../risk'], { relativeTo: this.route });
    }
}